<template>
  <div class="exam-wrapper">
    <div class="header" ref="domRef">
      {{
        decodeURIComponent(
          route.query.keyword_name ? route.query.keyword_name + '' : '',
        ).slice(0, 50)
      }}
    </div>
    <div class="exam-content">
      <div class="exam-left">
        <div class="wrapper-qs">
          <div class="exam-item" v-if="questionList.length">
            <div class="content" style="padding: 0 10px 0 0">
              <div class="qs-header-title">
                <div>
                  <el-button type="primary" id="top" round>
                    {{ query.page }}.
                    {{ STATIC_QUESTION_TYPE[selectedQuestion.type] }}
                  </el-button>
                  【{{ STATIC_QSRANK_TYPE[selectedQuestion.difficulty] }}】
                  <el-text
                    v-if="QuestionType.fill === selectedQuestion.type"
                    style="color: var(--el-color-warning); margin-left: 10px"
                  >
                    注意事项：
                    {{
                      `(答案:${QuestionOrderText[selectedQuestion.is_order]})`
                    }}
                  </el-text>
                </div>
                <div
                  class="collect-qs"
                  style="cursor: pointer"
                  @click="handleCollect"
                >
                  <el-icon
                    v-if="selectedQuestion.in_collection !== 1"
                    size="24"
                  >
                    <Star />
                  </el-icon>
                  <el-icon v-else size="24" color="orange">
                    <Collect />
                  </el-icon>
                  <span>收藏</span>
                </div>
              </div>
              <div class="qs-content">
                <markdown-viewer
                  id="assistant-content"
                  :value="selectedQuestion.content"
                />
                <div
                  class="options"
                  v-if="
                    selectedQuestion.options && selectedQuestion.options?.length
                  "
                >
                  <div
                    class="opt-item"
                    v-for="(opt, index) in JSON.parse(selectedQuestion.options)"
                  >
                    <el-radio-group
                      v-if="
                        QuestionType.radio === selectedQuestion.type ||
                        QuestionType.judge === selectedQuestion.type
                      "
                      @change="handleChangeRadio(index)"
                      v-model="selectedQuestion.user_answer"
                    >
                      <el-radio :value="mapIndex[index]">
                        <markdown-viewer
                          :id="`opt-item` + index"
                          :value="opt"
                        />
                      </el-radio>
                    </el-radio-group>
                    <div
                      v-else-if="
                        QuestionType.checkbox === selectedQuestion.type
                      "
                      style="display: flex; align-items: center; gap: 10px"
                    >
                      <el-checkbox-group
                        v-model="selectedQuestion.user_answer"
                        @change="handleChangeMultiple(index)"
                      >
                        <el-checkbox :value="mapIndex[index]">
                          <markdown-viewer
                            :id="`opt-item` + index"
                            :value="opt"
                          />
                        </el-checkbox>
                      </el-checkbox-group>
                      <!-- <markdown-viewer
                          :id="`opt-item` + index"
                          :value="opt"
                        /> -->
                    </div>
                  </div>
                </div>
                <!-- 填空题 -->
                <div
                  v-if="QuestionType.fill === selectedQuestion.type"
                  class="fill"
                >
                  <div
                    class="fill-item"
                    style="margin-bottom: 10px; position: relative"
                    v-for="(item, index) in selectedQuestion.fills"
                  >
                    <p
                      style="
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                      "
                    >
                      <span> 答案: {{ index + 1 }}</span>
                      <InsertIcon
                        @click.native="handleInsertFormula('fill', item)"
                      />
                    </p>
                    <div class="question-item-li" style="width: 100%">
                      <div
                        @click="handleFocus(item, index)"
                        style="border-bottom: 1px solid #ccc; width: 100%"
                        v-if="item.fill && !item.showInput"
                      >
                        <markdown-viewer
                          @click="handleFocus(item, index)"
                          :id="`answer` + index"
                          :value="item.fill"
                        />
                      </div>
                      <div
                        v-else-if="item.showInput || !item.fill"
                        style="flex: 1"
                      >
                        <div
                          style="border-bottom: 1px solid #ccc; width: 100%"
                          class="fill-input-container"
                        >
                          <el-input
                            :ref="
                              (ref) => {
                                mapInputRef(ref, item.id)
                              }
                            "
                            type="textarea"
                            v-model="item.fill"
                            placeholder="请输入答案"
                            @change="handleChangeFill(item, index)"
                            @blur="handleBlurFill(item, index)"
                            @focus="handleFocusFill(item, index)"
                            class="fill-input"
                            resize="none"
                            autosize
                            :input-style="{
                              border: 'none',
                              boxShadow: 'none !important',
                            }"
                          ></el-input>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <!-- 简答题 -->
                <div v-if="selectedQuestion.type === QuestionType.short">
                  <p
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    "
                  >
                    <span>答案: </span>
                    <InsertIcon
                      @click.native="handleInsertFormula('shortAnswer')"
                    />
                  </p>
                  <div
                    @click="handleFocusShort(selectedQuestion)"
                    style="border-bottom: 1px solid #ccc; width: 100%"
                    v-if="
                      selectedQuestion.user_answer &&
                      !selectedQuestion.showInput
                    "
                  >
                    <markdown-viewer
                      @click="handleFocusShort(selectedQuestion)"
                      :value="selectedQuestion.user_answer"
                    />
                  </div>
                  <el-input
                    v-else-if="
                      !selectedQuestion.user_answer ||
                      selectedQuestion.showInput
                    "
                    type="textarea"
                    v-model="selectedQuestion.user_answer"
                    placeholder="请输入答案"
                    @change="handleChangeShort"
                    @blur="selectedQuestion.showInput = false"
                    class="fill-input"
                    :input-style="{
                      border: 'none',
                    }"
                  ></el-input>
                </div>
              </div>
            </div>
            <div v-if="showAnswer" class="anwer-explain">
              <div class="answer flex align-items-center">
                <div style="width: 50px; flex-shrink: 0">答案:</div>
                <markdown-viewer id="answer" :value="selectedQuestion.answer" />
              </div>
              <div class="explain">
                <div style="width: 50px; flex-shrink: 0">解析:</div>
                <markdown-viewer
                  id="explain"
                  :value="selectedQuestion.analysis"
                />
              </div>
            </div>
          </div>
          <div class="answer-explain" v-if="questionList.length">
            <!-- v-if="
                selectedQuestion.user_answer !== null &&
                selectedQuestion.user_answer !== undefined
              " -->
            <el-button
              type="primary"
              v-if="selectedQuestion.is_right !== 0 || isAnswer"
              @click="handleViewAnswer"
            >
              {{ showAnswer ? '收起' : '查看答案及解析' }}
            </el-button>
            <el-button type="danger" @click="handleAddErrorQuestion">
              {{ selectedQuestion.in_wrong_book === 1 ? '移出' : '加入' }}错题本
            </el-button>
            <el-button type="primary" @click="handleViewAnswerCard">
              查看答题卡
            </el-button>
          </div>
          <div
            v-if="questionList.length"
            class="pre-next"
            style="
              width: 100%;
              display: flex;
              justify-content: space-between;
              padding: 10px;
            "
          >
            <div>
              <el-button
                type="primary"
                v-if="query.page > 1"
                @click="handlePre"
              >
                上一题
              </el-button>
            </div>
            <div>
              <el-button type="warning" @click="submitAnswer">
                提交答案
              </el-button>
              <el-button
                type="primary"
                v-if="query.page * query.limit < totalCount"
                @click="handleNext"
              >
                下一题
              </el-button>
            </div>
          </div>
          <el-empty v-else :description="'暂无题目'"></el-empty>
        </div>
        <div class="answer-card" v-if="!showAnswerCard">
          <div style="display: flex; gap: 10px">
            <div
              v-for="(item, i) in labels"
              :key="i"
              class="do"
              style="
                display: flex;
                align-items: center;
                color: #999;
                gap: 4px;
                font-size: 14px;
              "
            >
              <div
                class="is-do"
                :style="{
                  backgroundColor: item.color,
                  border: !item.color && '1px solid #999',
                }"
              ></div>
              <span>{{ item.label }}</span>
            </div>
            <template v-if="questionList.length">
              <span class="answer-card-total">
                答对：
                <span style="color: var(--el-color-success)">
                  {{ allData.answerSummary.right }}
                </span>
              </span>
              <span class="answer-card-total"
                >答错：
                <span style="color: var(--el-color-danger)">
                  {{ allData.answerSummary.wrong }}</span
                >
              </span>
              <span class="answer-card-total">
                正确率：
                <span style="color: var(--el-color-primary)">
                  {{
                    Number(allData.answerSummary.right_rate * 100).toFixed(2)
                  }}%
                </span>
              </span>
            </template>
          </div>
          <el-scrollbar height="400px" v-if="questionList.length">
            <div v-for="(item, index) in allData.questionType">
              <div style="padding: 10px 0; text-align: start">
                <span style="font-size: 14px; margin-left: -8px">
                  【{{ STATIC_QUESTION_TYPE[item.type] }}】
                </span>
                <span style="color: #999; font-size: 12px">
                  （共{{ item.children.length }}题）
                </span>
              </div>
              <div style="display: flex; flex-wrap: wrap; gap: 4px">
                <div
                  class="question-num"
                  v-for="(child, i) in item.children"
                  @click="handleChangeQuestion(child, i)"
                  :class="[
                    query.page === child.sort + 1 ? 'active-sort' : '',
                    child.is_right == QuestionIsRight.undo
                      ? ''
                      : child.is_right == QuestionIsRight.right
                      ? 'correct'
                      : 'error',
                  ]"
                >
                  <span>{{ child.sort + 1 }}</span>
                </div>
              </div>
            </div>
          </el-scrollbar>
          <el-empty v-else></el-empty>
        </div>
      </div>
      <el-affix :offset="20">
        <div class="exam-right">
          <div style="display: flex; align-items: center">
            <h3>答题</h3>
            :
            <span v-if="questionList.length">
              {{ query.page }} / {{ totalCount }}
            </span>
            <span v-else style="font-size: 14px; color: #aaa; margin-left: 6px"
              >暂无题目</span
            >
          </div>
          <div class="refer">
            <h3>参考资料:</h3>
            <el-skeleton
              style="width: 100%"
              :loading="referLoading"
              animated
              :throttle="{ leading: 500, initVal: true }"
            >
              <template #template>
                <div style="padding: 10px">
                  <div
                    v-for="i in 3"
                    :key="i"
                    style="
                      display: flex;
                      align-items: center;
                      justify-items: space-between;
                      margin-top: 16px;
                    "
                  >
                    <el-skeleton-item
                      variant="text"
                      style="margin-right: 16px; width: 140px; height: 60px"
                    />
                    <el-skeleton-item
                      variant="text"
                      style="width: 140px; height: 60px"
                    />
                  </div>
                </div>
              </template>
              <template #default>
                <div
                  class="data-item-wrapper"
                  style="
                    display: flex;
                    flex-wrap: wrap;
                    gap: 20px;
                    margin-top: 10px;
                  "
                  v-if="dataHots.length"
                >
                  <div
                    class="item"
                    v-for="(item, index) in dataHots"
                    :key="index"
                    @click="handleViewData(item)"
                  >
                    <el-icon
                      size="32"
                      style="width: 32px; color: var(--el-color-primary)"
                    >
                      <Document />
                    </el-icon>
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      :content="item.filename"
                      placement="top-start"
                    >
                      <el-text
                        line-clamp="2"
                        style="flex: 1; padding-left: 6px"
                      >
                        {{ item.filename }}
                      </el-text>
                    </el-tooltip>
                  </div>
                </div>
                <el-empty v-else description="暂无参考资料" />
              </template>
            </el-skeleton>
            <div
              style="margin: 10px; text-align: center"
              v-if="referTotalCount > 6"
            >
              <el-button style="min-width: 100px" @click="getMoreRefers">
                查看更多
              </el-button>
            </div>
          </div>
        </div>
      </el-affix>
    </div>
  </div>
  <insert-formula
    v-model:visible="officialVisible"
    @insert-formula="insertOfficial"
  />
  <DataModal v-model:visible="dialogVisible" v-model:data="referList" />
</template>
<script setup lang="ts">
import { ref, nextTick, onMounted, reactive } from 'vue'
import MarkdownViewer from '@/components/markdown-viewer/index.vue'
import Collect from '@/icons/Collect.vue'
import {
  QuestionType,
  STATIC_QUESTION_TYPE,
  CollectOrError,
  QuestionIsRight,
  QuestionOrderText,
  STATIC_QSRANK_TYPE,
} from '@/enum/study'
import { useRoute, useRouter } from 'vue-router'
import {
  httpExamQuestions,
  httpReplyQuestion,
  httpCollectOrAddError,
  httpRemoveCollectOrError,
  httpExamRecords,
  httpLastRecord,
  httpRefers,
} from '@/api/study'
import InsertFormula from './components/InsertFormula.vue'
import InsertIcon from './components/InsertFormulaIcon.vue'
import DataModal from './data-modal.vue'
import { ElMessage } from 'element-plus'

const officialVisible = ref(false)
const selectedQuestion = ref<any>({})
const showAnswer = ref(false) // 查看答案及解析
const showAnswerCard = ref(false) // 查看答题卡
const questionList = ref([])
const domRef = ref(null)
const route = useRoute()
const router = useRouter()
const dialogVisible = ref(false)
const referList = ref([]) // 参考资料列表
const totalCount = ref(0)
const initList = ref([])
const dataHots = ref([]) // 参考资料
const referTotalCount = ref(0)
const referLoading = ref(false)
type PromiseType = {
  list: any[]
  total: number
}
const query = reactive({
  page: 1,
  limit: 1,
})
const queryRefers = reactive({
  page: 1,
  limit: 20,
})
const mapIndex = {
  0: 'A',
  1: 'B',
  2: 'C',
  3: 'D',
  4: 'E',
  5: 'F',
  6: 'G',
  7: 'H',
}
const labels = [
  { label: '答错', color: `var(--el-color-danger)` },
  { label: '答对', color: `var(--el-color-success)` },
  { label: '未做', color: `` },
]
const isAnswer = ref(false)
/**
 * 题目作答
 * @param question
 */
const reply = async (question) => {
  await httpReplyQuestion(question)
}
const mapRefs = ref({})
const mapInputRef = (ref, id) => {
  mapRefs.value[id] = ref
}
const handleFocus = (item, index) => {
  item.showInput = true
  nextTick(() => {
    mapRefs.value[item.id].focus()
  })
}
const handleBlurFill = (item, index) => {
  item.showInput = false
}
const handleFocusFill = (item, index) => {
  item.showInput = true
}
// 填空题
const handleChangeFill = async (item, index?: number) => {
  // item.showInput = true
  // let qIndex = initList.value.findIndex(
  //   (item) => item.id === selectedQuestion.value.id,
  // )
  // let data = {
  //   question_id: selectedQuestion.value.id,
  //   user_answer: selectedQuestion.value.fills
  //     .map((item) => item.fill)
  //     .join('|'),
  //   keyword_id: 1, // TODO: route.query.keyword_id
  //   page: query.page,
  //   limit: query.limit,
  //   index: qIndex,
  // }
  // await reply(data)
  // updateAnswerCardByFillShort()
}
const formatMultiAnswer = (answer = '') => {
  return answer.toUpperCase().split('').sort().join('')
}
// 单选题 判断题
const handleChangeRadio = (index) => {
  // let qIndex = initList.value.findIndex(
  //   (item) => item.id === selectedQuestion.value.id,
  // )
  // let data = {
  //   question_id: selectedQuestion.value.id,
  //   user_answer: selectedQuestion.value.user_answer,
  //   keyword_id: 1, // TODO: route.query.keyword_id
  //   page: query.page,
  //   limit: query.limit,
  //   index: qIndex,
  // }
  // reply(data)
  // updateAnswerCard()
}
// 多选题
const handleChangeMultiple = (index) => {
  // let qIndex = initList.value.findIndex(
  //   (item) => item.id === selectedQuestion.value.id,
  // )
  // let data = {
  //   question_id: selectedQuestion.value.id,
  //   user_answer: selectedQuestion.value.user_answer.join(''),
  //   keyword_id: 1, // TODO: route.query.keyword_id
  //   page: query.page,
  //   limit: query.limit,
  //   index: qIndex,
  // }
  // let answer = selectedQuestion.value.user_answer.join('')
  // selectedQuestion.value.select = formatMultiAnswer(answer)
  // reply(data)
  // updateAnswerCard()
}
// 简答题
const handleFocusShort = (selectedQuestion) => {
  selectedQuestion.showInput = true
}
const handleChangeShort = (value) => {
  // let qIndex = initList.value.findIndex(
  //   (item) => item.id === selectedQuestion.value.id,
  // )
  // let data = {
  //   question_id: selectedQuestion.value.id,
  //   user_answer: selectedQuestion.value.user_answer,
  //   keyword_id: 1, // TODO: route.query.keyword_id
  //   page: query.page,
  //   limit: query.limit,
  //   index: qIndex,
  // }
  // reply(data)
  // updateAnswerCardByFillShort()
}
/**
 * 提交答案
 */
const submitAnswer = async () => {
  let qIndex = initList.value.findIndex(
    (item) => item.id === selectedQuestion.value.id,
  )
  let data = {
    question_id: selectedQuestion.value.id,
    user_answer: selectedQuestion.value.user_answer,
    keyword_id: route.query.keyword_id, // TODO:
    page: query.page,
    limit: query.limit,
    index: qIndex,
  }
  if (selectedQuestion.value.type === QuestionType.checkbox) {
    data.user_answer = selectedQuestion.value.user_answer.join('')
    let answer = selectedQuestion.value.user_answer.join('')
    selectedQuestion.value.select = formatMultiAnswer(answer)
  } else if (selectedQuestion.value.type === QuestionType.fill) {
    data.user_answer = selectedQuestion.value.fills
      .map((item) => item.fill)
      .join('|')
    let FLAG = selectedQuestion.value.fills.some((item) => item.fill)
    if (!FLAG) {
      return ElMessage.error('请先作答')
    }
  }
  if (!data.user_answer) {
    return ElMessage.error('请先作答')
  }

  if (selectedQuestion.value.initAnswer === data.user_answer) {
    return
  }
  await reply(data)
  isAnswer.value = true
  if (
    selectedQuestion.value.type === QuestionType.fill ||
    selectedQuestion.value.type === QuestionType.short
  ) {
    updateAnswerCardByFillShort()
  } else {
    updateAnswerCard()
  }
}
/**
 * 前端更新答题卡 单选 多选 判断
 */
const updateAnswerCard = () => {
  let question = selectedQuestion.value
  let type = question.type
  let arr = allData.questionType[type - 1].children
  let obj = arr.find((item) => item.id === question.id)
  if (obj) {
    let answer =
      question.type === QuestionType.checkbox
        ? formatMultiAnswer(question.user_answer.join(''))
        : question.user_answer
    obj.is_right =
      question.answer === answer ? QuestionIsRight.right : QuestionIsRight.error
  }
}

/**
 * 加入到收藏夹
 * @param collect
 */
const handleCollect = async (collect) => {
  selectedQuestion.value.in_collection === 1
    ? (selectedQuestion.value.in_collection = 0)
    : (selectedQuestion.value.in_collection = 1)
  if (selectedQuestion.value.in_collection === 1) {
    httpCollectOrAddError({
      question_id: selectedQuestion.value.id,
      type: CollectOrError.collect,
    })
  } else {
    httpRemoveCollectOrError({
      question_id: selectedQuestion.value.id,
      type: CollectOrError.collect,
    })
  }
}
const handleNext = async () => {
  // 1.如果没作答不走这个函数 2.如果作答才走
  if (selectedQuestion.value.type === QuestionType.fill) {
    let FLAG = selectedQuestion.value.fills.some((item) => item.fill)
    FLAG && submitAnswer()
  } else {
    selectedQuestion.value.user_answer && submitAnswer()
  }
  showAnswer.value = false
  showAnswerCard.value = false
  if (query.page > totalCount.value) {
    return
  }
  query.page += 1
  await getQuestions()
}
const handlePre = async () => {
  showAnswer.value = false
  showAnswerCard.value = false
  if (query.page > 1) {
    query.page -= 1
    await getQuestions()
  }
}
/**
 * 切换题目
 * @param qs 题目
 * @param index
 */
const handleChangeQuestion = (child, index) => {
  query.page = child.sort + 1
  getQuestions()
}
const handleViewAnswer = async () => {
  showAnswer.value = !showAnswer.value
  await nextTick()
  if (!showAnswer.value) {
    setTimeout(() => {
      domRef.value.scrollIntoView({ behavior: 'smooth', block: 'start' })
      window.scrollTo({
        top: 0,
        behavior: 'smooth', // 平滑滚动
      })
    }, 2000)
  }
}
/**
 * 加入到错题
 */
const handleAddErrorQuestion = () => {
  selectedQuestion.value.in_wrong_book === 1
    ? (selectedQuestion.value.in_wrong_book = 0)
    : (selectedQuestion.value.in_wrong_book = 1)
  if (selectedQuestion.value.in_wrong_book === 1) {
    httpCollectOrAddError({
      question_id: selectedQuestion.value.id,
      type: CollectOrError.error,
    })
  } else {
    httpRemoveCollectOrError({
      question_id: selectedQuestion.value.id,
      type: CollectOrError.error,
    })
  }
}
/**
 * 查看答题卡
 */
const handleViewAnswerCard = () => {
  showAnswerCard.value = !showAnswerCard.value
}
const sortArr = (arr) => {
  let radio = arr.filter((item) => item.type === QuestionType.radio)
  let checkbox = arr.filter((item) => {
    if (item.type === QuestionType.checkbox) {
      item.select = formatMultiAnswer(item.user_answer)
      let arr = item.user_answer.split('')
      item.user_answer = arr
      return item
    }
  })
  let judge = arr.filter((item) => item.type === QuestionType.judge)
  let fill = arr.filter((item) => {
    if (item.type === QuestionType.fill) {
      let arr = item.user_answer.split('|')
      item.fills = item.answer.split('|').map((item, index) => {
        return {
          index,
          id: index,
          fill: arr.length && arr[index] ? arr[index].trim() : '',
        }
      })
      return item
    }
  })

  let short = arr.filter((item) => item.type === QuestionType.short)
  return [...radio, ...checkbox, ...judge, ...fill, ...short].map(
    (item, index) => ({
      ...item,
      // sort: index + 1,
      questionIndex: index,
      sort:
        query.page === 1
          ? index + 1
          : (query.page - 1) * query.limit + index + 1,
      initAnswer: item.user_answer,
    }),
  )
}
const mergedArray = (arr) => {
  return arr.reduce((acc, current, index) => {
    const existing = acc.find((item) => item.type === current.type)
    if (existing) {
      existing.children.push({ ...current, sort: index })
    } else {
      acc.push({ type: current.type, children: [{ ...current, sort: index }] })
    }
    return acc
  }, [])
}
const getQuestions = async () => {
  const res: any = await httpExamQuestions({
    // keyword_id: Number(route.query.keyword_id),
    keyword_id: route.query.keyword_id,
    ...query,
  })
  if (res) {
    totalCount.value = res.total
    initList.value = JSON.parse(JSON.stringify(res.list))
    questionList.value = sortArr(res.list)
    // allQuestion.value = mergedArray(
    //   JSON.parse(JSON.stringify(questionList.value)),
    // )
    selectedQuestion.value = questionList.value[0]
  }
}
const insertNode = reactive<any>({
  name: '',
  data: {},
})

const insertOfficial = (value) => {
  value = ` \\(${value}\\) `
  if (insertNode.name === 'fill') {
    const index = selectedQuestion.value.fills.findIndex(
      (item) => item.id === insertNode.data?.id,
    )
    if (index > -1) {
      selectedQuestion.value.fills[index].fill += value
      // handleChangeFill(selectedQuestion.value.fills[index])
      selectedQuestion.value.fills[index].showInput = false
    }
  } else if (insertNode.name === 'shortAnswer') {
    selectedQuestion.value.user_answer += value
  }
}
const handleInsertFormula = (params, item?: any) => {
  officialVisible.value = true
  // nextTick(() => {
  //   item.showInput = true
  // })
  if (params === 'fill') {
    insertNode.name = 'fill'
    insertNode.data = item
  } else if (params === 'shortAnswer') {
    insertNode.name = 'shortAnswer'
  }
}
const getLastRecord = async () => {
  const res: any = await httpLastRecord({
    keyword_id: route.query.keyword_id,
  })
  if (res) {
    let lastPage = res.list[0]?.page || 1
    query.page = lastPage
  }
}
const allData = reactive<any>({
  answerSummary: {},
  list: [],
  questionType: {},
})
const getAllQuestion = async () => {
  const res: any = await httpExamRecords({
    keyword_id: route.query.keyword_id,
  })
  if (res) {
    let row = res.list[0]
    allData.answerSummary = row.answerSummary
    allData.list = row.list
    allData.questionType = mergedArray(row.list)
  }
}
const updateAnswerCardByFillShort = () => {
  getAllQuestion()
}

/**
 * 获取题目参考资料
 */

const getRefers = async (query) => {
  return new Promise<PromiseType>(async (resolve, reject) => {
    try {
      const res: any = await httpRefers({
        course_id: Number(route.query.course_id),
        department_id: Number(route.query.pid),
        node_id: Number(route.query.keyword_id),
        ...query,
      })
      resolve({ list: res.list, total: res.total })
    } catch (err) {
      reject(err)
    } finally {
      referLoading.value = false
    }
  })
}

const getMoreRefers = async () => {
  dialogVisible.value = true
  const res = await getRefers(queryRefers)
  if (res) {
    referList.value = res.list
  }
}
const getHotRefers = async () => {
  const res = await getRefers({
    page: 1,
    limit: 6,
  })
  if (res) {
    dataHots.value = res.list
    referTotalCount.value = res.total
  }
}
const handleViewData = (item) => {
  const url = router.resolve({
    path: '/study/data-items',
    query: {
      data_id: item.id,
      course_id: Number(route.query.course_id),
    },
  })
  window.open(url.href, '_blank')
}
onMounted(async () => {
  getHotRefers()
  await getLastRecord()
  getQuestions()
  getAllQuestion()
})
</script>

<style scoped lang="scss">
.exam-wrapper {
  height: 100%;
  .header {
    height: 40px;
    line-height: 40px;
    font-weight: bold;
    font-size: 18px;
    border-bottom: 1px solid #ccc;
  }
  .exam-content {
    display: flex;
    justify-content: space-between;
    // height: calc(100% - 40px);
    .exam-left {
      min-width: 900px;
      width: calc(100% - 400px);
      height: 100%;
      padding: 10px 0;
      .wrapper-qs {
        box-shadow: var(--el-box-shadow-light);
        border-radius: var(--el-border-radius-base);
        background-color: #fff;
        padding: 10px;
      }

      .qs-content {
        .opt-item {
          margin-bottom: 10px;
        }
        :deep(.el-radio) {
          height: fit-content !important;
        }
        :deep(.el-checkbox) {
          height: fit-content !important;
        }
      }
      .exam-item {
        .qs-header-title {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 10px;

          .collect-qs {
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 4px 10px;
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }
        .anwer-explain {
          // box-shadow: var(--el-box-shadow-light);
          // border-radius: var(--el-border-radius-base);
          // background-color: #fff;
          // padding: 10px;
          .answer {
            word-wrap: break-word;
            padding: 10px 0;
          }
          .explain {
            word-wrap: break-word;
            padding: 10px 10px 10px 0;
          }
        }
      }
      .answer-explain {
        padding: 10px;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
      }
      .answer-card {
        height: 440px;
        box-shadow: var(--el-box-shadow-light);
        border-radius: var(--el-border-radius-base);
        background-color: #fff;
        padding: 10px;
        margin-top: 20px;
        .active-sort {
          border: 2px solid #409eff !important;
        }
        .is-do {
          width: 16px;
          height: 16px;
          border-radius: 2px;
          // background: linear-gradient(
          //   to right,
          //   var(--el-color-danger),
          //   var(--el-color-success)
          // );
        }
        .answer-card-total {
          color: #999;
          font-size: 14px;
        }
        .question-num {
          border: 1px solid #ccc;
          width: 40px;
          height: 30px;
          background-color: #fff;
          border: 1px solid #ccc;
          display: flex;
          align-items: center;
          justify-content: center;
          text-align: center;
          line-height: 30px;
          cursor: pointer;
          &.correct {
            background-color: var(--el-color-success);
            color: #fff;
          }
          &.error {
            background-color: var(--el-color-danger);
            color: #fff;
          }
        }
      }
    }
    .exam-right {
      width: 340px;
      padding: 10px;
      margin-top: 10px;
      box-shadow: var(--el-box-shadow-light);
      border-radius: var(--el-border-radius-base);
      background-color: #fff;
      .refer {
        margin-top: 10px;
        border-top: 1px solid #ccc;
      }
      .data-item-wrapper {
        height: fit-content;
        .item {
          width: 140px;
          height: 60px;
          display: flex;
          align-items: baseline;
          box-shadow: var(--el-box-shadow-light);
          padding: 10px 4px;
          cursor: pointer;
          &:hover {
            transform: scale(1.02);
          }
          span {
            height: 100%;
          }
        }
      }
    }
  }
}
.katex-expression {
  cursor: pointer;
  margin: 5px;
  padding: 5px;
  border: 1px solid #ccc;
  display: inline-block;
}
.katex-expression:hover {
  background-color: #f0f0f0;
}
.fill-input {
  border: none !important;
}
.fill-input-container {
  position: relative;
  :deep(.el-input__wrapper) {
    box-shadow: none !important;
    border: none !important;
    padding: 0 !important;
  }
}
:deep(.el-textarea__inner) {
  position: relative;
  padding-right: 30px !important;
}
</style>
